package com.pro.addresslist.ui.activity;


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.pro.addresslist.R;
import com.pro.addresslist.dal.bll.ContactInfoBLL;
import com.pro.addresslist.dal.bll.FriendshipBLL;
import com.pro.addresslist.dal.model.ContactInfo;
import com.pro.addresslist.dal.model.ContactInfoBySqlite;
import com.pro.addresslist.dal.model.Friendship;
import com.pro.addresslist.dal.model.SortModel;
import com.pro.addresslist.sqllite.ContactInfoServise;
import com.pro.addresslist.tools.NetUtil;
import com.pro.addresslist.tools.constantUtil;
import com.pro.addresslist.tools.runNumber;
import com.pro.addresslist.ui.adapter.CommonAdapter;
import com.pro.addresslist.ui.adapter.ViewHolder;
import com.pro.addresslist.ui.common.BaseActivity;
import com.pro.addresslist.ui.view.CharacterParser;
import com.pro.addresslist.ui.view.ClearEditText;
import com.pro.addresslist.ui.view.PinyinComparator;
import com.pro.addresslist.ui.view.SideBar;
import com.pro.addresslist.ui.view.SideBar.OnTouchingLetterChangedListener;

public class ContactsActivity extends BaseActivity {

	private  Friendship ff=new Friendship();
	private Button btnSave;
	private Button btnNew;
	private Button btnqueding;
	private ListView sortListView;
	private CommonAdapter<ContactInfoBySqlite> adapter;
	private android.widget.CheckBox CheckBox;
	private Boolean editMode=true;
	private TextView tvLetter;
	private TextView tvTitle;
	private TextView img;
	private SideBar sideBar;
	private TextView dialog;
	private ClearEditText mClearEditText;
	private List<Friendship> friends;
	private String contactId;
	private String id;//朋友ID
	private String friendName;
	SmsManager sManager;
//    //checkbox选中的数据  
//    HashMap<Integer, SortModel> state = new HashMap<Integer, SortModel>();
	HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();  
    String options="选择的项是:";  
    private static int position;
    //判断群发还是新增朋友？
    private boolean isQunFa;
    private String gkdy="";
    //选中号码
    ArrayList<String> SelectPhoneList = new ArrayList<String>();
    private int posiont=0;
    //朋友过滤
    List<String> friendnum=new ArrayList<String>();
	/**
	 *汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<ContactInfoBySqlite> SourceDateList=new ArrayList<ContactInfoBySqlite>();
	
	/**
	 * 根据拼音来排列ListView里面的数据类 
	 */
	private PinyinComparator pinyinComparator;
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case constantUtil.Num_SelectContactByAll:
				
				/**
				 * 这里边是刷新的一系列数据准备，准备好后进行刷新
				 **/
				List<ContactInfoBySqlite> listcons=(List<ContactInfoBySqlite>) msg.obj;
				for(ContactInfoBySqlite con:listcons){
					SourceDateList.add(con);
				}
				Log.i("libs", "shu"+SourceDateList.size());
				// 根据a-z进行排序源数据
				Collections.sort(SourceDateList, pinyinComparator);
				adapter.notifyDataSetChanged();
				disMissDialog();
				break;
			case constantUtil.Num_SelectContactBygk:
				/**
				 * 这里边是刷新的一系列数据准备，准备好后进行刷新
				 **/
				List<ContactInfoBySqlite> listcongk=(List<ContactInfoBySqlite>) msg.obj;
				for(ContactInfoBySqlite con:listcongk){
					SourceDateList.add(con);
				}
				// 根据a-z进行排序源数据
				Collections.sort(SourceDateList, pinyinComparator);
				adapter.notifyDataSetChanged();
				break;
			case constantUtil.Num_SelectContactBydy:
				/**
				 * 这里边是刷新的一系列数据准备，准备好后进行刷新
				 **/
				List<ContactInfoBySqlite> listcondy=(List<ContactInfoBySqlite>) msg.obj;
				for(ContactInfoBySqlite con:listcondy){
					SourceDateList.add(con);
				}
				// 根据a-z进行排序源数据
				Collections.sort(SourceDateList, pinyinComparator);
				adapter.notifyDataSetChanged();
				break;
			case constantUtil.Num_SelectContactByFriend:
				/**
				 * 这里边是刷新的一系列数据准备，准备好后进行刷新
				 **/
				List<ContactInfoBySqlite> listconfriend=(List<ContactInfoBySqlite>) msg.obj;
				for(ContactInfoBySqlite con:listconfriend){
					SourceDateList.add(con);
				}
				// 根据a-z进行排序源数据
				Collections.sort(SourceDateList, pinyinComparator);
				adapter.notifyDataSetChanged();
				disMissDialog();
				break;
			case constantUtil.Num_DelContactByID:
				String result= (String)msg.obj;
				if(result.equals("succeed")){
        			 ContactInfoServise ser = new ContactInfoServise(mContext);
        			 int id=msg.arg1;
        			 ser.DelContactByIDTrue(id);
        			 Toast.makeText(mContext,"删除成功！",Toast.LENGTH_SHORT).show();
	 					SourceDateList.remove(posiont);
	 					adapter.notifyDataSetChanged();
        		 }
        		 else{
        			 Toast.makeText(getApplication(),"删除失败！",Toast.LENGTH_SHORT).show();
        		 }
			break;
			default:
				break;
			}
		}
	};
	class myThreadAll implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer=new ContactInfoServise(mContext);
			List<ContactInfoBySqlite> listcon=conSer.SelectContactByAll();
			Message message = new Message();   
	        message.what = constantUtil.Num_SelectContactByAll;
	        message.obj=listcon;
	        mHandler.sendMessage(message);
		}
	}
	class myThreadgk implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer=new ContactInfoServise(mContext);
			List<ContactInfoBySqlite> listcon=conSer.SelectContactBygk(gkdy);
			Message message = new Message();   
	        message.what = constantUtil.Num_SelectContactBygk;
	        message.obj=listcon;
	        mHandler.sendMessage(message);
		}
	}
	class myThreaddy implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer=new ContactInfoServise(mContext);
			List<ContactInfoBySqlite> listcon=conSer.SelectContactBydy(gkdy);
			Message message = new Message();   
	        message.what = constantUtil.Num_SelectContactBydy;
	        message.obj=listcon;
	        mHandler.sendMessage(message);
		}
	}
	class myThreadFriend implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer=new ContactInfoServise(mContext);
			List<ContactInfoBySqlite> listcon=conSer.SelectContactByFriend(friendnum);
			Message message = new Message();   
	        message.what = constantUtil.Num_SelectContactByFriend;
	        message.obj=listcon;
	        mHandler.sendMessage(message);
		}
	}
	public class ReceiveBroadCast extends BroadcastReceiver 
	{ 
	  
	        @Override 
	        public void onReceive(Context context, Intent intent) 
	        { 
	        	String action = intent.getAction();
	        		if(action.equals("AddBatchFriendShip")){
	        			String  result= (String)intent.getSerializableExtra("result");
		        		 if(result.equals("succeed")){
		        			 Toast.makeText(mContext, "添加成功！！", Toast.LENGTH_SHORT).show();
		        			 finish(); 
		        		 }
		        		 else{
		        			 Toast.makeText(mContext, "添加失败！！", Toast.LENGTH_SHORT).show();
		        			 
		        		 }
	        		}
	        		//查找联系人朋友  
	        		if(action.equals("SelectFriendShip")){
	        			List<Friendship>  friends=(List<Friendship>) intent.getSerializableExtra("parameter");
	        			if(friends.size()!=0){
	        			String ss=friends.get(0).get_ContactMainID();
	        			friendnum.add(ss);
		        		for(Friendship ff:friends){
		        			friendnum.add(ff.get_ContactChildrenID());
		        		}
		        		new Thread(new myThreadFriend()).start();
	        			}
	        			else {
							friendnum.add(contactId);
							new Thread(new myThreadFriend()).start();
						}
	        		}
	        	}
	        } 

	@Override
	public int getLayout() {

		return R.layout.activity_contacts;
		
	}
	 void initview(){
		 btnSave=(Button) findViewById(R.id.btnSave);
		 btnNew=(Button) findViewById(R.id.btnNew);
		 btnqueding=(Button) findViewById(R.id.btnqueding);
		
		}
	 void initclick(){
		 btnSave.setOnClickListener(this);
		 btnqueding.setOnClickListener(this);
		 btnNew.setOnClickListener(this);
		 }

	@Override
	public void OnActCreate(Bundle savedInstanceState) {
		setTtile("联系人");
		setLeftImageBack();

		initview();
		initclick();
		Intent intent=getIntent();
		String action=intent.getStringExtra("action");
		gkdy = intent.getStringExtra("gkdy");
		 if(action!=null){
		if(action.equals("dy")){
			Log.i("libs", gkdy+"归口地域");
			new Thread(new myThreaddy()).start();
		}
		if(action.equals("gk")){
			new Thread(new myThreadgk()).start();
		}
		if(action.equals("friends")){
			//添加朋友	
			 contactId=intent.getStringExtra("ContactId");
			FriendshipBLL.SelectFriendShip(mContext,contactId);				
			if(true){
				editMode=!editMode;
			}
			setTtile("联系人");
			showProgressDialog();
		}
		 }
		if(action==null){
			 new Thread(new myThreadAll()).start();
			 showProgressDialog();
		        }
		ReceiveBroadCast receiveBroadCast = new ReceiveBroadCast(); 
        IntentFilter filter = new IntentFilter(); 
        filter.addAction("AddBatchFriendShip");
        filter.addAction("SelectFriendShip");
        registerReceiver(receiveBroadCast, filter);
        
		//实例化汉字转拼音类 
		characterParser = CharacterParser.getInstance();
		
		pinyinComparator = new PinyinComparator();
		
		sideBar = (SideBar) findViewById(R.id.sidrbar);
		dialog = (TextView) findViewById(R.id.dialog);
		sideBar.setTextView(dialog);
		
		//设置右侧触摸监听 
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
			
			@Override
			public void onTouchingLetterChanged(String s) {
				//该字母首次出现的位置 
				int position = getPositionForSection(s.charAt(0));
				if(position != -1){
					sortListView.setSelection(position);
				}
				
			}
		});
		
		sortListView = (ListView) findViewById(R.id.country_lvcountry);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			//	ContactsActivity.position=position;
				//这里要利用adapter.getItem(position)来获取当前position所对应的对象 
				//Toast.makeText(getApplication(), ((SortModel)adapter.getItem(position)).getName(), Toast.LENGTH_SHORT).show();
				Intent intent=new Intent(mContext,PersonalInformationActivity.class);
				intent.putExtra("contactID", SourceDateList.get(position).get_id()+"");
				startActivity(intent);
				finish();
			}
		});
		sortListView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				posiont = arg2;
				sortListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
					@Override
					public void onCreateContextMenu(ContextMenu arg0,
							View arg1, ContextMenuInfo arg2) {
						MenuInflater inflator = new MenuInflater(
								ContactsActivity.this);
						inflator.inflate(R.menu.relation_menu, arg0);
					}
				});
				return false;
			}
		});
		
		adapter=new CommonAdapter<ContactInfoBySqlite>(ContactsActivity.this, SourceDateList, R.layout.item) {
			
			
			@Override
			public void convert(final ViewHolder holder, final ContactInfoBySqlite t) {
				// TODO Auto-generated method stub
				
				position=holder.getPosition();
				
				Log.i("gj", "Checked"+position);
				tvLetter=(TextView)holder.getView(R.id.catalog);
				tvTitle=(TextView)holder.getView(R.id.title);
				img=(TextView)holder.getView(R.id.img);
				CheckBox = (android.widget.CheckBox) holder.getView(R.id.checkBox);
				CheckBox.setChecked(t.isCheck);
				//复选框点击事件
				CheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {					
					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						// TODO Auto-generated method stub
						 if (isChecked) {  
			                    state.put(holder.getPosition(), isChecked);  
			                    //Log.i("mt", holder.getPosition()+"add:"+isChecked);
			                    SourceDateList.get(holder.getPosition()).isCheck=isChecked;
			                } else {  
			                    state.put(holder.getPosition(), isChecked); 
			                    SourceDateList.get(holder.getPosition()).isCheck=isChecked;
			                    //Log.i("mt", holder.getPosition()+"remove:"+isChecked);
			                }  
					}
				});
				if (editMode) {
					CheckBox.setVisibility(View.GONE);
					btnSave.setVisibility(View.VISIBLE);
					btnNew.setVisibility(View.VISIBLE);
					btnqueding.setVisibility(View.GONE);
					
				} else {
					CheckBox.setVisibility(View.VISIBLE);
					btnSave.setVisibility(View.GONE);
					btnNew.setVisibility(View.GONE);
					btnqueding.setVisibility(View.VISIBLE);
				}
				
				 //根据position获取分类的首字母的char ascii值 
				int section = getSectionForPosition(position);
				
				//如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
				if(position == getPositionForSection(section)){
					tvLetter.setVisibility(View.VISIBLE);
					tvLetter.setText(t.get_NAMEPY());
				}else{
					tvLetter.setVisibility(View.GONE);
				}
			
				tvTitle.setText(t.get_Name());
				img.setText(t.get_Name().substring(0, 1));
			}
			
		};
		sortListView.setAdapter(adapter);
		
		mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);
		
		//根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				//当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		
 }

	// 长按菜单响应函数
		@Override
		public boolean onContextItemSelected(MenuItem item){
			switch (item.getItemId()) {
			case R.id.del:
				int id=SourceDateList.get(posiont).get_id();
				String conId=SourceDateList.get(posiont).get_ContactID();
				ContactInfoServise ser = new ContactInfoServise(mContext);
				int state=ser.SelectStateByid(id);
				if(state==1){
					Boolean re=ser.DelContactByIDTrue(id);
					if(re){
						Toast.makeText(mContext,"删除成功！",Toast.LENGTH_SHORT).show();
						SourceDateList.remove(posiont);
						adapter.notifyDataSetChanged();
					}
					else {
						Toast.makeText(mContext,"删除失败！",Toast.LENGTH_SHORT).show();
					}
				}
				else{
					if(NetUtil.isNetworkAvailable(mContext)){
						ContactInfoBLL.DelContactByID(mContext, conId, id,mHandler);
					}
					else{
						Toast.makeText(mContext,"当前无网络，不能执行删除！",Toast.LENGTH_SHORT).show();
					}
				}
				break;
			case R.id.updata:
				Intent in = new Intent(ContactsActivity.this, NewContactsActivity.class);
				in.putExtra("actions", "edtcon");
				in.putExtra("conid", SourceDateList.get(posiont).get_id());
				startActivity(in);
				finish();
				break;
			default:
				break;
			}
			return super.onContextItemSelected(item);
		}

	@Override
	public void OnViewClick(View v) {
		switch (v.getId()) {
		case R.id.btnSave:
			isQunFa=true;
			if(editMode){
			editMode=!editMode;
			}
			adapter.notifyDataSetChanged();
			setLeftImageHide();
			setTtile("联系人");
			setLeftText("取消",new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					setLeftHide();
					setLeftImageBack();
					setRightHide();
					editMode = true;
					adapter.notifyDataSetChanged();
				}
			});
			OnClickListener listener = new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Toast.makeText(mContext, "全选", Toast.LENGTH_SHORT).show();
					SelectPhoneList.clear();
					for(int i=0;i<SourceDateList.size();i++){
						state.put(i, true);
						SourceDateList.get(i).isCheck=true;
						
					}
					adapter.notifyDataSetChanged();
					
				}
			};
			setRightText("全选", listener);
			break;
		case R.id.btnqueding:
			if(isQunFa==true){
				//Toast.makeText(ContactsActivity.this, "群发", Toast.LENGTH_LONG).show();
				showProgressDialog();
				setSelectList();
				for(int i=0;i<SourceDateList.size();i++){
					if(state.get(i)!=null&&state.get(i)==true){
						SelectPhoneList.add(SourceDateList.get(i).get_MobileEn().split(",")[0]);
					}
				}
				if(SelectPhoneList.size()==0){
					Toast.makeText(ContactsActivity.this, "请至少选中一个！", Toast.LENGTH_SHORT).show();
					break;
				}
				//发送短信
				// 获得所有选择的联系人
				disMissDialog();
				Intent intents = new Intent(ContactsActivity.this,SendMsgActivity.class);
				intents.putStringArrayListExtra("telNum", SelectPhoneList);
				startActivity(intents);
				finish();
			}else{
			   addFriends();
			}
			break;
			case R.id.btnNew:
				Intent newcont = new Intent();
				newcont.setClass(getApplicationContext(),
						NewContactsActivity.class);
				startActivity(newcont);
				finish();
				break;
		default:
			break;
		}
	}
	/**
	 * 根据ListView的当前位置获取分类的首字母的char ascii值
	 */
	public int getSectionForPosition(int position) {
		return SourceDateList.get(position).get_NAMEPY().charAt(0);
	}

	/**
	 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
	 */
	public int getPositionForSection(int section) {
		for (int i = 0; i < SourceDateList.size(); i++) {
			String sortStr = SourceDateList.get(i).get_NAMEPY();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}
		
		return -1;
	}
	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * @param filterStr
	 */
	private void filterData(String filterStr){
		List<ContactInfoBySqlite> filterDateList = new ArrayList<ContactInfoBySqlite>();
		
		if(TextUtils.isEmpty(filterStr)){
			filterDateList = SourceDateList;
		}else{
			filterDateList.clear();
			for(ContactInfoBySqlite sortModel : SourceDateList){
				String name = sortModel.get_Name();
				if(name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())){
					filterDateList.add(sortModel);
				}
			}
		}
		
		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
	}
	/**
	 * 为ListView填充数据
	 * @param date
	 * @return
	 */
	private List<SortModel> filledData(List<ContactInfo> date){
		List<SortModel> mSortList = new ArrayList<SortModel>();
		
		for(int i=0; i<date.size(); i++){
			SortModel sortModel = new SortModel();
			sortModel.setName(date.get(i).get_Name());
			sortModel.setId(date.get(i).get_ContactID());
			sortModel.setTel(date.get(i).get_Mobile());
			Log.i("libs", date.get(i).get_Name());
			//汉字转换成拼音
			String pinyin = characterParser.getSelling(date.get(i).get_Name());
			Log.i("libs", date.get(i).get_Name()+pinyin);
			String sortString = pinyin.substring(0, 1).toUpperCase();
			
			// 正则表达式，判断首字母是否是英文字母
			if(sortString.matches("[A-Z]")){
				sortModel.setSortLetters(sortString.toUpperCase());
			}else{
				sortModel.setSortLetters("#");
			}
			
			mSortList.add(sortModel);
		}
		return mSortList;
		
	}
    public void addFriends(){
    	List<Friendship> listf=new ArrayList<Friendship>();
    	Iterator iter = state.entrySet().iterator();  
    	while (iter.hasNext()) {  
    	    Map.Entry entry = (Map.Entry) iter.next();  
    	   
    	    int key = (int) entry.getKey(); 
    	    if(state.get(key).booleanValue()==true){
    	    Friendship friend=new Friendship();
    	    runNumber run = new runNumber();
			//生成随机id。
    	    friend.set_FriendshipID(run.getMaxID());
    	    friend.set_ContactMainID(contactId);
    	    friend.set_ContactChildrenID(SourceDateList.get(key).get_ContactID());
    	    listf.add(friend);
    	    }
    	} 
    	if(listf.size()==0){
    	Toast.makeText(ContactsActivity.this, "请选择您要添加的朋友", Toast.LENGTH_SHORT).show();
    	}else{
    		FriendshipBLL.AddBatchFriendShip(mContext,listf);
    	}
//    	String ffs=null;
//    	 ffs+=SourceDateList.get(position).getName();
//    	for(int j=0;j<SourceDateList.size();j++){
//        	if(state.get(j)!=null){  
//        	@SuppressWarnings("unchecked")
//        	SortModel map=(SortModel)  SourceDateList.get(j);  
//        	String ids=map.getId();
//        	friendName+=map.getName();
//        	id+=ids;
//        	options+="\n"+id+"名字："+friendName;
//        	}  
//        	}  
//    	Toast.makeText(getApplicationContext(), "id的值为："+id+"姓名为："+ffs, Toast.LENGTH_LONG).show(); 
//    	friends=new ArrayList<Friendship>();
//    	ff.set_ContactChildrenID(id);
//    	ff.set_ContactMainID(contactId);
//    	//ff.set_FriendshipID("");
//    	friends.add(ff);
//    	ReceiveBroadCast receiveBroadCast = new ReceiveBroadCast(); 
//        IntentFilter filter = new IntentFilter(); 
//        filter.addAction("AddBatchFriendShip");
//        registerReceiver(receiveBroadCast, filter); 
//        FriendshipBLL.AddBatchFriendShip(mContext,friends);
//        
//        	//显示选择内容  
//        	Toast.makeText(getApplicationContext(), options, Toast.LENGTH_LONG).show();  
        	}  
    
	private void setSelectList() {
		if(SelectPhoneList.size()!=0){
			SelectPhoneList.clear();
		}
	}
    	
    }


